﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;
using System.Windows.Media;


namespace Fayshine.VA.Views.SearchStatistics.Year
{
    public partial class YearMonthShopCompare : Page
    {
        private StatisticsReportViewModel m_ViewModel;
        private DateTime m_Date;
        public YearMonthShopCompare()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(YearMonthShopCompare_Loaded);
        }

        private void YearMonthShopCompare_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            cmbYear.ItemsSource = FayshineManager.Instance.GetYearSource();
            cmbYear.SelectedValue = DateTime.Now.Year;

            m_ViewModel = new StatisticsReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                SetYearGateChart();

                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                List<int> monitorAreaIDs = new List<int>();
                selectAreaExt.each(s => { monitorAreaIDs.Add(s.ID); });

                spGrid.Children.Clear();
                Grid tableGrid = GetTableGrid();
                //tableGrid.Width = 1000;

                Grid topGrid = GetTopGrid(monitorAreaIDs);
                topGrid.SetValue(Grid.RowProperty, 0);

                Grid contentGrid = GetContentGrid(monitorAreaIDs.Count);
                contentGrid.SetValue(Grid.RowProperty, 1);
                FillTimeColumnInContentGrid(contentGrid);
                FillPassengerInContentGrid(contentGrid, monitorAreaIDs);

                tableGrid.Children.Add(topGrid);
                tableGrid.Children.Add(contentGrid);
                spGrid.Children.Add(tableGrid);

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }
            });
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            m_ViewModel.AreaExtends.each(a => a.IsSelected = true);
            m_Date = new DateTime((int)cmbYear.SelectedValue, 1, 1);

            m_ViewModel.RefreshYearGateReport(true, m_Date);

        }

        private void SetYearGateChart()
        {
            bool isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
            string subTitle = cmbInorOut.SelectedIndex == 0 ? "进客流对比" : "出客流对比";
            RenderAs renderAs = cmbStyle.SelectedIndex == 0 ? RenderAs.Line : RenderAs.Column;
            int year = (int)cmbYear.SelectedValue;

            string title1 = GetChartSubTitle();
            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = year + "年" + "各月 各店铺" + subTitle;
            vcChart1.Titles.Add(vcChart1Title);

            lblTitle.Text = vcChart1Title.Text;

            var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            List<int> monitorAreaIDs = new List<int>();
            selectAreaExt.each(s => { monitorAreaIDs.Add(s.ID); });
            bool isSingleArea = monitorAreaIDs.Count == 1 ? true : false;

            selectAreaExt.each(s =>
            {
                var source = m_ViewModel.GetYearHistoryPassengerFlowByGate(isSingleArea, year, s.ID);
                vcChart1.Series.Add(GetDataSeries(s.Name, isIn, renderAs, source));
            });

        }

        private DataSeries GetDataSeries(string title, bool isIn, RenderAs randerAs, List<HistoryPassengerFlow> source)
        {
            DataSeries series = ChartHelper.GetDataSeries(randerAs, title, ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            if (isIn)
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            }
            else
            {
                series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            }
            series.DataSource = source;

            return series;
        }

        private string GetChartSubTitle()
        {
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            return title1;
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

        private Grid GetTableGrid()
        {
            Grid grid = new Grid();
            grid.Name = "tableGrid";
            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            grid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            //grid.ShowGridLines = true;
            grid.Width = 900;
            grid.Margin = new Thickness(30, 10, 30, 20);
            grid.RowDefinitions.Add(GetRowDefinition(40));
            RowDefinition row1 = new RowDefinition();
            row1.Height = new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
            grid.RowDefinitions.Add(row1);

            GridBorderHelper.ShowBorder(grid);
            return grid;
        }

        private Grid GetTopGrid(List<int> gateOrAreas)
        {
            int count = gateOrAreas.Count;

            Grid grid = new Grid();
            grid.Name = "topGrid";
            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            grid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            grid.Margin = new Thickness(0, 0, 0, 0);
            grid.Background = new SolidColorBrush(Color.FromArgb(255, 255, 245, 238));

            ColumnDefinition column1 = new ColumnDefinition();
            column1.Width = new System.Windows.GridLength(100, System.Windows.GridUnitType.Pixel);
            grid.ColumnDefinitions.Add(column1);

            int index = 0;
            index = 0;
            decimal percent = (decimal)1 / count;
            percent = Math.Round(percent, 2);
            while (index < count)
            {
                grid.ColumnDefinitions.Add(GetColumnDefinition((double)percent));
                index++;
            }

            //set first column [时段]
            TextBlock timeText = GetTextBlock(-1, 0, "月份");
            grid.Children.Add(timeText);

            //Set gate Golumns
            index = 1;
            gateOrAreas.each(g =>
            {

                Grid columnGrid = new Grid();
                columnGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                columnGrid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
                columnGrid.Margin = new Thickness(0, 0, 0, 0);
                //columnGrid.ShowGridLines = true;
                columnGrid.RowDefinitions.Add(GetRowDefinitionStart(1));
                // columnGrid.RowDefinitions.Add(GetRowDefinitionStart(0.5));
                string gateName = m_ViewModel.GetAreaName(g);
                TextBlock gateText = GetTextBlock(0, -1, gateName);
                columnGrid.Children.Add(gateText);
                // Grid inOrOutGrid = GetInOrOutGrid(1, -1);
                // GridBorderHelper.ShowBorder(inOrOutGrid);
                // columnGrid.Children.Add(inOrOutGrid);

                columnGrid.SetValue(Grid.ColumnProperty, index);
                GridBorderHelper.ShowBorder(columnGrid);
                grid.Children.Add(columnGrid);
                index++;

            });

            GridBorderHelper.ShowBorder(grid);
            return grid;
        }

        private void FillTimeColumnInContentGrid(Grid contentGrid)
        {
            DateTime startTime = m_Date;
            DateTime endTime = m_Date.AddYears(1);
            TextBlock tempText = null;
            string textStr = string.Empty;

            int index = 0;
            while (startTime < endTime)
            {
                textStr = startTime.Month + "月";

                tempText = new TextBlock();
                tempText.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                tempText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                tempText.FontSize = 10;
                tempText.Text = textStr;
                tempText.SetValue(Grid.RowProperty, index);
                tempText.SetValue(Grid.ColumnProperty, 0);

                contentGrid.Children.Add(tempText);

                index++;
                startTime = startTime.AddMonths(1);
            }

        }

        private void FillPassengerInContentGrid(Grid contentGrid, List<int> areaIDs)
        {
            TextBlock tempText = null;
            string textStr = string.Empty;

            int columnIndex = 1;
            List<HistoryPassengerFlow> tempPassengerFlows = null;
            HistoryPassengerFlow tempPassengerFlow = null;
            areaIDs.each(id =>
            {
                tempPassengerFlows = m_ViewModel.GetYearHistoryPassengerFlowByGate(false, m_Date.Year, id);
                

                AddSourceToDataGrid(contentGrid, tempPassengerFlows, columnIndex);
                //columnIndex = columnIndex+3;
                columnIndex++;
            });

            //Set All
            //DateTime startTime2 = new DateTime(startDatePicker.SelectedDate.Value.Year,
            //                  startDatePicker.SelectedDate.Value.Month,
            //                  startDatePicker.SelectedDate.Value.Day,
            //                  0, 0, 0);
            //DateTime endTime2 = startTime2.AddDays(1);
            //tempPassengerFlows = m_ViewModel.GetDayAllPassengerFlow(startTime2, endTime2, 60);
            //AddSourceToDataGrid(contentGrid, tempPassengerFlows, columnIndex);

            //columnIndex = columnIndex + 3;

        }

        private void AddSourceToDataGrid(Grid contentGrid, List<HistoryPassengerFlow> tempPassengerFlows, int columnIndex)
        {
            int rowIndex = 0;
            DateTime startTime = m_Date;
            DateTime endTime = startTime.AddYears(1);
            bool isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
            HistoryPassengerFlow tempPassengerFlow = null;
            while (startTime < endTime)
            {
                tempPassengerFlow = tempPassengerFlows.Where(t => t.HistoryTime.Year == startTime.Year &&
                                                                  t.HistoryTime.Month == startTime.Month).FirstOrDefault();
                if (tempPassengerFlow != null)
                {
                    //In
                    if (isIn)
                    {
                        AddContentToDataGrid(tempPassengerFlow.InCount.ToString(), contentGrid, rowIndex, columnIndex);
                    }
                    else
                    {
                        AddContentToDataGrid(tempPassengerFlow.OutCount.ToString(), contentGrid, rowIndex, columnIndex);
                    }
                    //Out
                    //AddContentToDataGrid(tempPassengerFlow.OutCount.ToString(), contentGrid, rowIndex, columnIndex + 1);

                    //Differ
                    //AddContentToDataGrid((tempPassengerFlow.InCount - tempPassengerFlow.OutCount).ToString(), contentGrid, rowIndex, columnIndex + 2);
                }
                rowIndex++;
                startTime = startTime.AddMonths(1);
            }
            //All
            //int inSum = tempPassengerFlows.Sum(s => s.InCount);
            //int outSum = tempPassengerFlows.Sum(s => s.OutCount);
            // AddContentToDataGrid(inSum.ToString(), contentGrid, rowIndex, columnIndex);
            //AddContentToDataGrid(outSum.ToString(), contentGrid, rowIndex, columnIndex + 1);
            //AddContentToDataGrid((inSum - outSum).ToString(), contentGrid, rowIndex, columnIndex + 2);
        }

        private void AddContentToDataGrid(string text, Grid contentGrid, int rowIndex, int columnIndex)
        {
            TextBlock tempText = new TextBlock();
            tempText.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            tempText.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            tempText.Text = text;
            tempText.SetValue(Grid.RowProperty, rowIndex);
            tempText.SetValue(Grid.ColumnProperty, columnIndex);
            contentGrid.Children.Add(tempText);
        }

        private Grid GetContentGrid(int count)
        {
            Grid grid = new Grid();
            grid.Name = "contentGrid";
            grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            grid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
            grid.Margin = new Thickness(0, 0, 0, 0);

            int rowCount = 12;
            int columnCount = count + 1;

            int index = 0;
            while (index < rowCount)
            {
                grid.RowDefinitions.Add(GetRowDefinition(40));
                index++;
            }

            index = 0;
            decimal percent = (decimal)1 / count;
            percent = Math.Round(percent, 2);
            while (index < columnCount)
            {
                if (index == 0)
                {
                    ColumnDefinition column1 = new ColumnDefinition();
                    column1.Width = new System.Windows.GridLength(100, System.Windows.GridUnitType.Pixel);
                    grid.ColumnDefinitions.Add(column1);
                }
                else
                {
                    grid.ColumnDefinitions.Add(GetColumnDefinition((double)percent));
                }
                index++;
            }
            GridBorderHelper.ShowBorder(grid);
            return grid;
        }

        private RowDefinition GetRowDefinition(double height)
        {
            RowDefinition row1 = new RowDefinition();
            row1.Height = new System.Windows.GridLength(height, System.Windows.GridUnitType.Pixel);
            return row1;
        }

        private RowDefinition GetRowDefinitionStart(double height)
        {
            RowDefinition row1 = new RowDefinition();
            row1.Height = new System.Windows.GridLength(height, System.Windows.GridUnitType.Star);
            return row1;
        }

        private ColumnDefinition GetColumnDefinition(double width)
        {
            ColumnDefinition column1 = new ColumnDefinition();
            column1.Width = new System.Windows.GridLength(width, System.Windows.GridUnitType.Star);
            return column1;
        }

        private TextBlock GetTextBlock(int row, int column, string text)
        {
            TextBlock textBlock = new TextBlock();
            textBlock.Text = text;
            textBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            textBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            if (column >= 0)
            {
                textBlock.SetValue(Grid.ColumnProperty, column);
            }
            if (row >= 0)
            {
                textBlock.SetValue(Grid.RowProperty, row);
            }

            return textBlock;
        }


    }
}
